import 'package:flutter/material.dart';

class FittedBoxRoute extends StatelessWidget {
  const FittedBoxRoute({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('空间适配 FittedBox'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 30.0),
              child: Row(children: [Text('xx' * 30)]), //文本长度超出 Row 的最大宽度会溢出
            ),
            const SizedBox(height: 30),
            wContainer(BoxFit.none),
            const Text('Wendux'),
            const SizedBox(height: 30),
            wContainer(BoxFit.contain),
            const Text('Flutter中国'),
            const SizedBox(height: 30),
            wRow(' 90000000000000000 '),
            const SizedBox(height: 30),
            FittedBox(child: wRow(' 90000000000000000 ')),
            const SizedBox(height: 30),
            wRow(' 800 '),
            const SizedBox(height: 30),
            FittedBox(child: wRow(' 800 ')),
            const SizedBox(height: 30),
            wRow(' 90000000000000000 '),
            const SizedBox(height: 30),
            SingleLineFittedBox(child: wRow(' 90000000000000000 ')),
            const SizedBox(height: 30),
            wRow(' 800 '),
            const SizedBox(height: 30),
            SingleLineFittedBox(child: wRow(' 800 ')),
            const SizedBox(height: 30),
          ],
        ),
      ),
    );
  }

  Container wContainer(BoxFit fit) {
    return Container(
      width: 80,
      height: 80,
      color: Colors.red,
      child: FittedBox(
        fit: fit,
        child: Container(
          height: 100,
          width: 90,
          color: Colors.blue,
        ),
      ),
    );
  }

  Widget wRow(String text) {
    Widget child = Text(text);
    child = Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[child, child, child],
    );
    return child;
  }
}

class SingleLineFittedBox extends StatelessWidget {
  const SingleLineFittedBox({Key? key, this.child}) : super(key: key);

  final Widget? child;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (_, constraints) {
        return FittedBox(
          child: ConstrainedBox(
            constraints: constraints.copyWith(
              minWidth: constraints.maxWidth,
              maxWidth: double.infinity,
            ),
            child: child,
          ),
        );
      },
    );
  }
}
